package com.ruoyi.specific.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.specific.domain.ImprovingUserPoints;
import com.ruoyi.specific.domain.bo.ImprovingUserPointsBo;
import com.ruoyi.specific.domain.vo.ImprovingUserPointsVo;
import com.ruoyi.specific.mapper.ImprovingUserPointsMapper;
import com.ruoyi.specific.service.IImprovingUserPointsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户积分Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-12
 */
@RequiredArgsConstructor
@Service
public class ImprovingUserPointsServiceImpl implements IImprovingUserPointsService {

    private final ImprovingUserPointsMapper baseMapper;

    /**
     * 查询用户积分
     */
    @Override
    public ImprovingUserPointsVo queryById(Long userId){
        return baseMapper.selectVoById(userId);
    }

    /**
     * 判断用户积分是否存在且大于指定积分数
     *
     * @param userId 用户ID
     * @param points 指定的积分数
     * @return 如果用户积分存在且大于指定积分数，返回true；否则返回false
     */
    @Override
    public boolean checkUserPointsGreaterThanOrEqualTo(Long userId, BigDecimal points) {
        ImprovingUserPointsVo userPoints = baseMapper.selectVoById(userId);
        return userPoints != null && userPoints.getAvailable().compareTo(points) >= 0;
    }

    /**
     * 扣除指定用户的积分
     *
     * @param userId 用户ID
     * @param points 要扣除的积分数
     * @return 如果扣除成功，返回true；否则返回false
     */
    @Override
    public boolean deductPointsByUserId(Long userId, BigDecimal points) {
        // 查询用户积分信息
        ImprovingUserPointsVo userPoints = baseMapper.selectVoById(userId);
        if (userPoints == null) {
            // 用户不存在，无法扣除积分
            return false;
        }

        BigDecimal availablePoints = userPoints.getAvailable();
        if (availablePoints.compareTo(points) < 0) {
            // 可用积分不足，无法完成扣除
            return false;
        }

        BigDecimal updatedAvailablePoints = availablePoints.subtract(points);
        ImprovingUserPoints update = new ImprovingUserPoints();
        update.setUserId(userId);
        update.setAvailable(updatedAvailablePoints);

        // 执行积分扣除操作
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 查询用户积分
     */
    @Override
    public List<ImprovingUserPointsVo> queryByIds(Collection<Long> userIds){
        return baseMapper.selectVoBatchIds(userIds);
    }

    /**
     * 查询用户积分
     */
    @Override
    public ImprovingUserPointsVo queryByUserName(String userName){
        LambdaQueryWrapper<ImprovingUserPoints> lqw = new LambdaQueryWrapper<>();
        lqw.eq(userName != null, ImprovingUserPoints::getUserName, userName);
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 查询用户积分列表
     */
    @Override
    public TableDataInfo<ImprovingUserPointsVo> queryPageList(ImprovingUserPointsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ImprovingUserPoints> lqw = buildQueryWrapper(bo);
        Page<ImprovingUserPointsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户积分列表
     */
    @Override
    public List<ImprovingUserPointsVo> queryList(ImprovingUserPointsBo bo) {
        LambdaQueryWrapper<ImprovingUserPoints> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ImprovingUserPoints> buildQueryWrapper(ImprovingUserPointsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ImprovingUserPoints> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserName() != null, ImprovingUserPoints::getUserName, bo.getUserName());
        lqw.eq(bo.getAvailable() != null, ImprovingUserPoints::getAvailable, bo.getAvailable());
        lqw.eq(bo.getTotal() != null, ImprovingUserPoints::getTotal, bo.getTotal());
        return lqw;
    }

    /**
     * 新增用户积分
     */
    @Override
    public Boolean insertByBo(ImprovingUserPointsBo bo) {
        ImprovingUserPoints add = BeanUtil.toBean(bo, ImprovingUserPoints.class);
        add.setAvailable(add.getTotal());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserId(add.getUserId());
        }
        return flag;
    }

    /**
     * 修改用户积分
     */
    @Override
    public Boolean updateByBo(ImprovingUserPointsBo bo) {
        ImprovingUserPointsVo userPoints = queryById(bo.getUserId());
        ImprovingUserPoints update = BeanUtil.toBean(bo, ImprovingUserPoints.class);

        BigDecimal oldAvailable = userPoints.getAvailable();
        // 计算新的Available值
        BigDecimal newAvailable = oldAvailable.add(update.getTotal()).subtract(userPoints.getTotal());
        update.setAvailable(newAvailable);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ImprovingUserPoints entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户积分
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
